package com.example.shiro.service.impl.user;

import com.example.shiro.domain.User;
import com.example.shiro.dto.AddUserDto;
import com.example.shiro.dto.UpdateUserDto;
import com.example.shiro.repository.UserRepository;
import com.example.shiro.response.ResponseMsg;
import com.example.shiro.service.user.UserService;
import com.example.shiro.utils.ObjectHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

/**
 * @ Author     ：jujh
 * @ Date       ：Created in 11:11 2018/10/31
 * @ Description：
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public List<User> findAll() {
        return userRepository.findAll();
    }

    @Override
    public void addUser(AddUserDto addUserDto) {
        User user = new User();
        BeanUtils.copyProperties(addUserDto, user);
        user.setWorkNum(System.currentTimeMillis() + "");
        userRepository.save(user);
    }

    @Override
    public ResponseMsg updateUser(UpdateUserDto updateUserDto) {
        ResponseMsg msg = new ResponseMsg();
        if (ObjectHelper.isEmpty(updateUserDto.getId())) {
            msg.setStatus(ResponseMsg.STATUS_FAILED);
            msg.setMsg("id不能为空！");
            return msg;
        }
        User user = userRepository.findOne(updateUserDto.getId());
        if (null == user) {
            msg.setStatus(ResponseMsg.STATUS_FAILED);
            msg.setMsg("用户信息不存在！");
            return msg;
        }
        BeanUtils.copyProperties(updateUserDto, user);
        userRepository.save(user);
        return msg;
    }

    @Override
    public ResponseMsg deleteUser(String id) {
        ResponseMsg msg = new ResponseMsg();
        if (ObjectHelper.isEmpty(id)) {
            msg.setStatus(ResponseMsg.STATUS_FAILED);
            msg.setMsg("id不能为空！");
            return msg;
        }
        User user = userRepository.findOne(id);
        if (null == user) {
            msg.setStatus(ResponseMsg.STATUS_FAILED);
            msg.setMsg("用户信息不存在！");
            return msg;
        }
        userRepository.delete(id);
        return msg;
    }
}
